package com.wtwd.campus.receiver;

import com.wtwd.campus.common.Constants;
import com.wtwd.campus.encryptnetty.EncryptChannelMap;
import com.wtwd.campus.entity.Command;
import com.wtwd.campus.entity.MqHeartBeatMessage;
import com.wtwd.campus.netty.ChannelMap;
import com.wtwd.campus.service.IRMFeignClientService;
import com.wtwd.campus.service.InjectFeignService;
import com.wtwd.campus.utils.InjectService;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class UploadNotLocateHeartReceiver implements Receiver {
    private static final Logger logger= LoggerFactory.getLogger(UploadNotLocateHeartReceiver.class);
    @Autowired
    private IRMFeignClientService irmFeignClientService;
    @Override
    public String parseMessage(String data) {
        //*WT,800115470000876,KA,172527,108,0,14,0,460,11,0,1,30501,124968449,108,030621,FFFDFFFF#
        //*WT,800115470000876,KA,172527,108,0,14,0,460,11,0,1,30501,124968449,108,030621,FFFDFFFF#
        //*WT,866248053275689,KA,173805,66,0,63,3158064,460,0,0,2,9365,176291087,66,0,0,0,200821,FDFFFFFF
        //分割字符串获取指令信息
        String[] split = data.split(",");
        String imei=split[1];
        String messageType = split[2];
        String commandNumber=split[3];
        String gsm=split[4];//协议中返回的事gsm，不知道是什么暂不处理
        String gpsnum=split[5];
        String battery=split[6];//电量
        String mcc=split[7];//MCC
        String mnc=split[8];//MCC
        String ta=split[9];//MCC
        String num=split[11];//MCC
        String lac=split[12];//MCC
        String cellId=split[13];//MCC
        String rxlev=split[14];//设备返回指令时间（时分秒）
        String date = split[split.length-2];//日月年
        String deviceStatus = split[split.length-1];//设备状态
        String lbsInfo="";
       /* int num2=Integer.valueOf(split[11]);
        for(int i = 0; i < num2; i++){
            if(!StringUtils.isBlank(lbsInfo)){
                lbsInfo = lbsInfo.concat("|");
            }
            lbsInfo = lbsInfo.concat(split[12+i*3]).concat(",").concat(split[13+i*3]).concat(",").concat(split[14+3*i]);
        }
        lbsInfo = split[8] + ","+transferToGaoDeMnc(mnc) +","+ lbsInfo;
        logger.info("基站信息" + lbsInfo);*/
        MqHeartBeatMessage mqHeartBeatMessage = new MqHeartBeatMessage();
        mqHeartBeatMessage.setImei(imei);
        mqHeartBeatMessage.setCommandNumber(commandNumber);
        mqHeartBeatMessage.setBattery(Integer.parseInt(battery));
        mqHeartBeatMessage.setDeviceDate(date);
        mqHeartBeatMessage.setDeviceTime(commandNumber);
        mqHeartBeatMessage.setStepNum(Integer.parseInt(mcc));
        mqHeartBeatMessage.setDeviceStatus(deviceStatus);
        mqHeartBeatMessage.setLbsInfo(lbsInfo);
        List<String> failedCommandKeys = new ArrayList<>();
        //从redis中查询出该设备所有的未回复的指令，判断重发次数及时间，再次进行发送
        Integer isEncrypted = InjectService.deviceIsEncrypt(imei);
        if(isEncrypted == null){
            return imei;
        }
        Channel channel = isEncrypted == 1 ? ChannelMap.get(imei) : EncryptChannelMap.get(imei);
        if(channel != null){
            Map<String, Object> commands =InjectService.getCommands(imei);
            if(commands != null && !commands.isEmpty()){
                for(Map.Entry<String,Object> entry :commands.entrySet()){
                    Command command = (Command)entry.getValue();
                    // 如果重发次数为2，则标记为失败
                    if(command.getRepeatCount()!=null &&command.getRepeatCount() == 2){
                        String result=entry.getKey();//类型-流水号
                   /*     if (command.getSequence() != null) {
                            //是白名单设置或者课堂模式
                            result = result.concat("-").concat(command.getSequence().toString());
                        }*/
                        failedCommandKeys.add(result);
                    }else{
                        // 解决部分null 或者之前为null的情况
                        Long lastSendTime = command.getLastSendTime() == null ? 0 : command.getLastSendTime();
                        // 上次发送超过15s的才重发
                        if(System.currentTimeMillis() - lastSendTime > 15 * 1000L){
                            channel.writeAndFlush(command.getContent());   // 发送
                            logger.info("重新下发指令："+command.getContent());
                            command.setLastSendTime(System.currentTimeMillis());
                            command.setRepeatCount(command.getRepeatCount() == null ? 1 : command.getRepeatCount() + 1);
                            InjectService.updateCommand(imei,entry.getKey(),command);
                        }
                    }
                }
            }
        }
        mqHeartBeatMessage.setFailedCmdList(failedCommandKeys);
        InjectFeignService.getIrmFeignClientService().upHeartBeatMessage(mqHeartBeatMessage);
        //将redis中的重发失败的指令删除，下次不再重发
        if (failedCommandKeys.size() > 0) {
            for (String s : failedCommandKeys) {
                // PBWLALL不在这删除的原因是放到后面Manager服务去进行删除
                if (s.contains(Constants.ALL_WHITELIST_NUMBER)) {
                    continue;
                }
                InjectService.delCommand(imei, s);
            }
        }
        return imei;
    }

    public static String transferToGaoDeMnc(String mnc) {
        String gaoDeMnc = "0";//0是中国移动，1是联通
        if(mnc.equals("01") || mnc.equals("06") || mnc.equals("09")) {
            gaoDeMnc = "1";
        }
        return gaoDeMnc;
    }
}
